package hc.j2me.load;

import hc.core.ContextManager;
import hc.core.MsgBuilder;
import hc.core.data.DataInputEvent;
import hc.core.util.HCURL;
import hc.j2me.Starter;
import hc.j2me.ui.MletPressShortPanel;
import hc.j2me.ui.PNGGameCanvas;
import hc.j2me.ui.UIManager;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class Mlet extends PNGGameCanvas implements SerialClass{
	private static final DataInputEvent dataInputEvent = new DataInputEvent();
	private static final byte[] mmBS = new byte[MsgBuilder.UDP_BYTE_SIZE];
	private static final int MIN_LEN = DataInputEvent.text_index - DataInputEvent.type_index;
	static {
		dataInputEvent.setBytes(mmBS);
	}
	
	public Mlet() {
		super(100);
		
		lm.append(screenSprite);
		
		shortPanel = new MletPressShortPanel(this, lm, screenSprite, _blockWidth, userMouseSplitWidth, _16);
	 }
	
	protected void keyPressed(int keyCode) {
		sendInputEvent(keyCode, getGameAction(keyCode), DataInputEvent.TYPE_TAG_KEY_PRESS_V_SCREEN);
	}
	
	public void keyReleased(int keyCode){
		sendInputEvent(keyCode, getGameAction(keyCode), DataInputEvent.TYPE_TAG_KEY_RELEASE_V_SCREEN);
		Starter.soundOK();
	}

	public void pointerPressed(final int x, final int y) {
		actionPointerPressed(x, y);
		
		sendInputEvent(x, y, DataInputEvent.TYPE_TAG_POINTER_PRESS_V_SCREEN);
	}
	
	public void pointerReleased(final int x, final int y) {
		if(actionPointerReleased(x, y) == R_OK){
			return;
		}

		sendInputEvent(x, y, DataInputEvent.TYPE_TAG_POINTER_RELEASE_V_SCREEN);
		Starter.soundOK();
	}
	
	public void pointerDragged(final int x, final int y) {
		super.pointerDragged(x, y);
		
		if(isDragged){
			sendInputEvent(x, y, DataInputEvent.TYPE_TAG_POINTER_DRAG_V_SCREEN);
			pointPressedX = x;
			pointPressedY = y;
		}
		//忽略细小变动，减少网络消耗
	}
	
	private void sendInputEvent(final int x, final int y, final int type){
		dataInputEvent.setType(type);
		dataInputEvent.setX(x);
		dataInputEvent.setY(y);
		ContextManager.getContextInstance().send(MsgBuilder.E_INPUT_EVENT, mmBS, MIN_LEN);
	}

	public void init(String screenID){
		setScreenID(screenID);
	}
	
	public void drawImage(int x, int y, int w, int h, byte[] bs, int offset, int len) {
		screenGraph.drawImage(Image.createImage(bs, offset, len), x, y,
				Graphics.TOP | Graphics.LEFT);
	}

	public static void enterActionCanvas(HCURL url){
		//尽管接收对象没有创建，但是考虑网络优先，所以先Send，后new接收者
		ContextManager.getContextInstance().send(MsgBuilder.E_GOTO_URL, url.url);

		try {
			Mlet ac = (Mlet)Class.forName("hc.j2me.load.Mlet").newInstance();
			UIManager.pushInAndSwithToNew(ac);
			
			ac.init(url.elementID);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
